package endpoint

import (
	"center/db"
	"common/pb"
	"context"
	"go.uber.org/zap"
)

func (s *MetainfoServer) ListObjects(ctx context.Context, req *pb.ObjectListRequest) (_ *pb.ObjectListResponse, err error) {
	defer func() {
		err = Error.Wrap(err)
		s.log.Info("ListObjects",
			zap.ByteString("bucket", req.Bucket), zap.Error(err))
	}()
	apiKey, err := s.validateAuth(ctx, req.Header)
	if err != nil {
		return nil, err
	}
	//检查bucket是否存在
	bucket, err := s.db.GetBucketByName(ctx, string(req.Bucket), apiKey.Head())
	if err != nil {
		return nil, err
	}

	objects, err := s.db.ListObjects(ctx, db.ListObjects{
		BucketId: bucket.ID,
		Limit:    int(req.Limit),
		Prefix:   req.EncryptedPrefix,
		Cursor:   req.Cursor,
	})

	if err != nil {
		return nil, err
	}
	data := new(pb.ObjectListResponse)
	data.Items = make([]*pb.ObjectListItem, len(objects))

	for i := range objects {
		data.Items[i] = &pb.ObjectListItem{
			EncryptedObjectKey: []byte(objects[i].EncryptObjectKey),
			PlainSize:          objects[i].PlainSize,
			StreamId:           objects[i].StreamId.Bytes(),
			Status:             int32(objects[i].Status),
		}
	}
	return data, nil
}
